package com.example.travel.controller;

import cn.hutool.Hutool;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.travel.common.AjaxResult;
import com.example.travel.common.Constants;
import com.example.travel.common.TableDataInfo;
import com.example.travel.domain.entity.Cart;
import com.example.travel.domain.entity.Orders;
import com.example.travel.domain.entity.Spot;
import com.example.travel.domain.entity.SpotOrders;
import com.example.travel.domain.entity.User;
import com.example.travel.domain.request.PageQuery;
import com.example.travel.interceptor.TokenUtils;
import com.example.travel.mapper.OrderSpotsMapper;
import com.example.travel.mapper.OrdersMapper;
import com.example.travel.service.ArticleService;
import com.example.travel.service.CartService;
import com.example.travel.service.OrdersService;
import com.example.travel.service.SpotService;
import io.swagger.annotations.Api;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author : LinQingLiang
 * @file : OrderController.java
 * @Since : 2023/2/23 17:36
 */

@RestController
@RequestMapping("/order")
@Api(tags = "订单管理")
public class OrderController extends BaseController{

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderSpotsMapper orderSpotsMapper;

    @Autowired
    private CartService cartService;

    @Autowired
    private SpotService spotService;



    @GetMapping("list")
    public TableDataInfo list(@Validated PageQuery pageQuery, @Param("name") String name){
        User currentUser = TokenUtils.getUser();
        Page page1 = ordersMapper.page(new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize()),name,currentUser.getRole(),currentUser.getId());
        return getDataTable(page1.getRecords(),page1.getTotal());
    }


    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@RequestBody Orders orders){

        Orders orders1 = new Orders();

        if(orders.getId() == null){
            Date date = new Date();
            orders.setTime(DateUtil.now());
            orders.setNo(DateUtil.format(date,"yyyyMMdd")+System.currentTimeMillis());
            orders.setUserId(TokenUtils.getUser().getId());

            //创建订单
            ordersMapper.insert(orders);
            BeanUtils.copyProperties(orders,orders1);

            List<Cart> carts = orders.getCarts();
            if(carts != null && !carts.isEmpty()){
                for (Cart cart:carts) {
                    SpotOrders spotOrders = new SpotOrders();
                    spotOrders.setSpotId(cart.getSpotId());
                    spotOrders.setNum(cart.getNum());
                    spotOrders.setOrderId(orders.getId());
                    orderSpotsMapper.insert(spotOrders);

                    //删除购物车的数据
                    cartService.removeById(cart.getId());
                }
            }
        }else{
            ordersMapper.updateById(orders);
        }
        return AjaxResult.success(orders1);
    }


    @GetMapping("/{id}")
    public AjaxResult selectById(@PathVariable Integer id){
        QueryWrapper<SpotOrders> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id",id);
        List<SpotOrders> spotOrders = orderSpotsMapper.selectList(wrapper);

        List<Spot> spotList = new ArrayList<>();
        for (SpotOrders spotOrder:spotOrders) {
            Integer spotId = spotOrder.getSpotId();
            Spot spot = spotService.getById(spotId);
            if (spot != null){
                spot.setNumber(spotOrder.getNum());
                spotList.add(spot);
            }
        }
        return AjaxResult.success(spotList);
    }


    @DeleteMapping("/deleteIds/{ids}")
    public AjaxResult deleteByIds(@PathVariable List<Integer> ids){
        return AjaxResult.success(ordersService.removeByIds(ids));
    }


    @DeleteMapping("/deleteById/{id}")
    public AjaxResult deleteById(@PathVariable Integer id){
        return AjaxResult.success(ordersService.removeById(id));
    }

    @GetMapping("/selectByOrder/{id}")
    public AjaxResult selectByOrder(@PathVariable Integer id){
        return AjaxResult.success(ordersService.getById(id));
    }

    @PutMapping("/updatePayState/{no}")
    public AjaxResult updatePayState(@PathVariable String no){
        String now = DateUtil.now();
        Orders orders = ordersMapper.selectByTranceNo(no);
        if (orders != null) {
            //hutool工具类,判断时间间隔
            Long between = DateUtil.between(DateUtil.parseDateTime(orders.getPaymentTime()),DateUtil.parseDateTime(now), DateUnit.DAY);
            if (between > Constants.DAY_COUNT){
                return AjaxResult.error(-1,"该订单已经超过了七天不支持退款");
            }
        }
        ordersMapper.updatePayState(no,"待退款",now);
        return AjaxResult.success("提出退款申请成功");
    }


    @PutMapping("/updateOrder")
    public AjaxResult updateOrder(@RequestBody Orders orders){
        return AjaxResult.success(ordersService.updateById(orders));
    }
}
